import os
import logging
import time

logging.basicConfig(level=logging.INFO)

from config_env import BASE_URL, USERNAME, PASSWORD, TOKEN
from service.token_service import get_token

# 初始化配置
MAX_RETRIES = 3
RETRY_DELAY = 2
HEADER = {}

logging.info(f"Connecting to ZenTao API at {BASE_URL}")

def initialize_token():
    global HEADER
    for attempt in range(MAX_RETRIES):
        try:
            _token = get_token(USERNAME, PASSWORD) if (USERNAME and PASSWORD) else TOKEN
            if _token:
                logging.info(f"Token初始化成功(尝试 {attempt + 1}/{MAX_RETRIES})")
                HEADER = {'Token': _token}
                logging.debug(f"使用的Token: {_token[:10]}...")
                return
            raise ValueError("获取到空token")
        except Exception as e:
            if attempt == MAX_RETRIES - 1:
                logging.error(f"Token初始化最终失败: {str(e)}")
                raise
            logging.warning(f"Token初始化失败(尝试 {attempt + 1}/{MAX_RETRIES}): {str(e)}")
            time.sleep(RETRY_DELAY)

# 执行初始化
try:
    initialize_token()
except Exception as e:
    if not TOKEN:
        raise ValueError(f"无法初始化token且无备用TOKEN: {str(e)}")
    HEADER = {'Token': TOKEN}
    logging.warning(f"使用备用TOKEN: {TOKEN[:10]}...")

logging.info("ZenTao MCP service initialized")
